<template>
  <el-card>
    <template #header>部门管理</template>

    <template>

      <!-- 1.0 操作表单 -->
      <el-row class="setting-btn">
        <el-col > <el-button size="mini" type="primary" @click="dialogVisible = true">添加部门</el-button>  </el-col>
        <el-col > <el-button size="mini" type="danger" @click="delAll">批量删除</el-button> </el-col>
        <el-col > <el-button size="mini" type="default" @click="toggleSelection()">取消选择</el-button> </el-col>
      </el-row>

      <!-- 2.0 表格数据 -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="部门名称" width="170"> </el-table-column>
        <el-table-column prop="details" label="部门详情"> </el-table-column>
        <el-table-column label="是否启用">
          <template v-slot="{ row }">
            <el-switch
              v-model="row.enable"
              @change="changeSate(row)"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" width="170">
          <template v-slot="{ row }">
            <span>{{ row.create_time | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改日期" width="170">
          <template v-slot="{ row }">
            <span>{{ row.update_time | dateFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序"> </el-table-column>
        <el-table-column label="操作" width="210">
          <template v-slot="{ row }">
            <el-button size="mini" type="primary" @click="editDepartment(row)">编辑</el-button>
            <el-button size="mini" type="warning" @click="showPower(row)">权限</el-button>
            <el-button size="mini" type="danger" @click="delDepartment(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 3.0 分页处理 -->
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 添加部门弹窗 -->
      <el-dialog title="添加部门" :visible.sync="dialogVisible" width="35%" @close="resetForm('addDepartment')">
        <el-form ref="addDepartment" :model="addForm" :rules="rules" label-width="80px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="部门级别" prop="parent_id">
            <el-input v-model="addForm.parent_id"></el-input>
          </el-form-item>
          <el-form-item label="部门描述" prop="details">
            <el-input v-model="addForm.details"></el-input>
          </el-form-item>
          <el-form-item label="部门排序" prop="sort">
            <el-input v-model="addForm.sort"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('addDepartment')">取 消</el-button>
          <el-button size="mini" type="primary" @click="submitForm('addDepartment')">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="编辑部门" :visible.sync="editDialogVisible" width="35%" @close="resetForm('editDepartment')">
        <el-form ref="editDepartment" :model="editForm" :rules="rules" label-width="80px">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="部门级别" prop="parent_id">
            <el-input v-model="editForm.parent_id"></el-input>
          </el-form-item>
          <el-form-item label="部门描述" prop="details">
            <el-input v-model="editForm.details"></el-input>
          </el-form-item>
          <el-form-item label="部门排序" prop="sort">
            <el-input v-model="editForm.sort"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="resetForm('editDepartment')">取 消</el-button>
          <el-button size="mini" type="primary" @click="editConfirm('editDepartment')">确认修改</el-button>
        </span>
      </el-dialog>

      <el-dialog title="选择权限" :visible.sync="chooseDepart" width="45%" @close="closeList">
        <el-tree
          v-if="showPanel"
          ref="tree"
          :data="treeData"
          show-checkbox
          node-key="powerId"
          :default-expanded-keys="expandedArr"
          :default-checked-keys="checkedArr"
          :props="defaultProps">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="closeList">取 消</el-button>
          <el-button size="mini" type="primary" @click="editConfirmPower">确认选择</el-button>
        </span>
      </el-dialog>
    </template>
  </el-card>
</template>

<script>
  import { getDeparts, addDeparts, delDeparts, batchDeparts, enableDeparts, disableDeparts, editDeparts, editDepartsPower } from '@/api/department'
  import { getPerList } from '@/api/powers'

  export default {
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableData: [],
        dialogVisible: false,
        editDialogVisible: false,
        chooseDepart: false,
        multipleSelection: [],
        addForm: {
          details: "",
          name: "",
          parent_id: 0,
          sort: 0
        },
        editForm: {
          details: "",
          name: "",
          parent_id: 0,
          sort: 0
        },
        rules: {
          name: [
            { required: true, message: '请输入部门名称', trigger: 'blur' },
            { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
          ]
        },
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        // 默认展开项
        expandedArr: [],
        // 默认选择项
        checkedArr: [],
        partId: '',
        showPanel: false
      }
    },
    created() {
      this.initData()
      this.getPowersList()
    },
    methods: {
      async getPowersList() {
        // 获取权限列表
        const res = await getPerList()
        // 递归算法完成数据嵌套
        function getData(arr, i) {
          let newArr = []
          if(Array.isArray(arr)) {
            newArr = res.data.filter(item => item.parentId === i)
            newArr.forEach(item => {
              const list = getData(newArr, item.powerId)
              if(list.length > 0) {
                item.children = list
              }
            })
          }
          return newArr
        }
        // 获取下拉框数据
        function getSelect(arr) {
          arr.forEach(item => {
            item.label = item.powerName
            item.value = item.powerId
            item.children && getSelect(item.children)
          })
        }
        this.treeData = getData(res.data, '0')
        getSelect(this.treeData)
      },
      async initData() {
        const { data, count } = await getDeparts({
          page: this.currentPage,
          limit: this.pageSize
        })
        this.tableData = data
        this.total = count
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          });
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.initData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.initData()
      },

      // 重置表单
      resetForm(formName) {
        this.dialogVisible = false
        this.editDialogVisible = false
        this.$refs[formName].resetFields()
      },
      // 添加用户
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const {success, msg} = await addDeparts(this.addForm)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        });
      },
      // 删除权限
      delDepartment(id) {
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {success, msg} = await delDeparts(id)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      // 批量删除
      delAll() {
        if(this.multipleSelection.length <= 0) return
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const ids = this.multipleSelection.map(item => item.id)
          const {success, msg} = await batchDeparts({ ids })
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.dialogVisible = false
            } else {
              this.$message.error(msg)
            }
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'})
        })
      },
      // 改变状态
      async changeSate(row) {
        if(row.enable) {
          const {success, msg} = await enableDeparts({ id: row.id })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }else {
          const {success, msg} = await disableDeparts({ id: row.id })
            if(success) {
              this.$message.success(msg)
            } else {
              this.$message.error(msg)
            }
        }
      },
      // 编辑用户
      editDepartment(row) {
        this.editForm = { ...row }
        this.editDialogVisible = true
      },
      // 确认修改
      editConfirm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const {success, msg} = await editDeparts(this.editForm)
            if(success) {
              this.$message.success(msg)
              this.initData()
              this.editDialogVisible = false
            } else {
              this.$message.error(msg)
            }
          } else {
            return false
          }
        });
      },
      showPower(row) {
        this.showPanel = true
        // 展示已选择的权限
        this.checkedArr = [...row.power_ids]
        this.chooseDepart = true
        this.partId = row.id
      },
      closeList() {
        this.checkedArr = []
        this.chooseDepart = false
        this.showPanel = false
      },
      async editConfirmPower() {
        // editDepartsPower
        const power_ids = this.$refs.tree.getCheckedNodes().map(item => item.powerId)
        const { success, msg } = await editDepartsPower({
          power_ids,
          department_id: this.partId
        })
        if(success) {
          this.$message.success(msg)
          this.initData()
          this.chooseDepart = false
        } else {
          this.$message.error(msg)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.setting-btn {
  display: flex;
  .el-col {
    width: 100px;
  }
}

.el-table {
  margin: 24px 0;
}

.el-dialog {
  .el-select {
    width: 100%;
  }
}
</style>